<template>
  <n-modal v-model:show="isVisible" title="编辑调拨单" preset="dialog" @close="onClose" style="height: 500px;width: 700px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container">
      <br>
      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="出库仓库：" path="outStoreId">
          <n-select
              v-model:value="form.outStoreId"
              style="width:180px"
              :options="outStores"
              filterable
              clearable
              @change="chooseOutStore"
          >
          </n-select>
        </n-form-item>
        <n-form-item label="调拨货物：" path="transferCommodityId" style="margin-left: 10px">
          <n-select
              v-model:value="form.transferCommodityId"
              style="width:180px"
              :options="commodities"
              filterable
              clearable
              @change="chooseTransferCommodity"
          >
          </n-select>
        </n-form-item>
        <n-form-item style="margin-left: 10px" label="调拨数量：" path="quantity">
          <n-input v-model:value="form.quantity"
                   style="width: 180px"
                   placeholder="请输入调拨数量"
          ></n-input>
        </n-form-item>

      </div>
      <div class="form-row">
        <n-form-item label="入库仓库：" path="storeName" >
          <n-select :options="inStores" style="width: 180px" v-model:value="form.inStoreId"></n-select>
        </n-form-item>
        <n-form-item label="调拨负责人：" path="adminId" style="margin-left: 10px">
          <n-select
              v-model:value="form.adminId"
              style="width:180px"
              :options="admins"
              filterable
              clearable
          >
          </n-select>
        </n-form-item>
      </div>
      <!-- 提交按钮 -->
      <div class="submit-row">
        <n-form-item>
          <n-button type="primary" native-type="submit" @click="handleSubmit">提交</n-button>
        </n-form-item>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
  import {onMounted, ref, watch} from 'vue';
  import { useMessage } from 'naive-ui';
  import api from "@/api/admin.js";
  import {List} from "echarts";
  import {useUserStore} from "@/store/index.js";

  const userStore = useUserStore()
  const loading = ref(true)
  const id = userStore.getId();
  const outStores=ref([])
  const admins=ref([])
  const inStores=ref([])
  const commodities=ref([])
  const emit = defineEmits(['updatePage'])
  const props = defineProps({
    show1: {
      type: Boolean,
      required: true,
    },
    onClose: {
      type: Function,
      required: true,
    },
    option: {
      type: List,
      require: true
    },
    storeTransfer:{
      type:Object,
      required:true,
    },
  });
  const form = ref({
    outStoreId:'',
    transferCommodityId:'',
    quantity:'',
    inStoreId:'',
    adminId:'',

  });

  const isVisible = ref(props.show1);
  watch(() => props.show1, (newVal) => {
    isVisible.value = newVal;
    if (newVal) {
      // 当对话框显示时，将传递过来的属性值填充到表单中
      form.value = { ...props.storeTransfer};
    }
  });
  const handleSubmit = async () => {
    try {
      const res = await api.updateStoreTransfer(
        {
          ...form.value,
        }
      )
      if(res.code === 200) {
        emit("updatePage")
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("添加失败！")
    }finally{
      clear()
      props.onClose();
    }
  };

  const clear = () => {
   form.value={
     outStoreId:'',
     transferCommodityId:'',
     quantity:'',
     inStoreId:'',
     adminId:'',
   }
    outStores.value=[]
    commodities.value=[]
    inStores.value=[]
    queryStoreList()
    queryStoreCommodityList()
  }
  const queryAdminList = async () => {
    loading.value = true
    try {
      const res = await api.findAdminByRole({
        role: 'STOREADMIN'
      })
      if(res.code === 200) {
        res.data.map((item)=>{
          admins.value.push({
            label: item.name,
            value: item.id
          })
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取管理员信息失败！")
    }finally{
      loading.value = false
    }
  }
  const queryStoreCommodityList = async () => {
    loading.value = true
    try {
      const res = await api.findAllInventory()
      if(res.code === 200) {
        res.data.map((item)=>{
          commodities.value.push({
            label: item.productName,
            value: item.id
          })
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取仓库信息失败！")
    }finally{
      loading.value = false
    }
  }
  const queryStoreList = async () => {
    loading.value = true
    try {
      const res = await api.findAllStore()
      if(res.code === 200) {
        res.data.map((item)=>{
          inStores.value.push({
            label: item.name,
            value: item.id
          })
          outStores.value.push({
            label: item.name,
            value: item.id
          })
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取仓库信息失败！")
    }finally{
      loading.value = false
    }
  }
  const chooseOutStore=async (outStoreId)=>{
    console.log(outStoreId)
    loading.value = true
    commodities.value=[];
    if(outStoreId!=null){
      try {
        const res = await api.findStoreCommodityByStoreId({params: {storeId: outStoreId}})
        const isHave=ref(false)
        if(res.code === 200) {
          if(res.data.length>0){
            res.data.map((item)=>{
              if(form.value.outStoreId==item.id){
                isHave.value=true;
              }
              commodities.value.push({
                label: item.productName,
                value: item.id
              })
            })
          }else{
            form.value.transferCommodityId=null;
            console.log(form.value.transferCommodityId)
          }
          if(!isHave.value){
            console.log(isHave.value)
            form.value.transferCommodityId=null;
          }
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("获取货物信息失败！")
      }finally{
        loading.value = false
      }
    }else {
      queryStoreCommodityList()
    }

  }
  const chooseTransferCommodity=async (transferCommodityId)=>{
    loading.value = true
    outStores.value=[];
    if(transferCommodityId!=null){
      try {
        const res = await api.findStoresByCommodityIds({params: {storeCommodityId: transferCommodityId}})
        const isHave=ref(false)
        if(res.code === 200) {
          if(res.data.length>0){
            outStores.value=[];
            res.data.map((item)=>{
              if(form.value.outStoreId==item.id){
                isHave.value=true;
              }
              outStores.value.push({
                label: item.name,
                value: item.id
              })
            })
          }else {
            form.value.outStoreId=null;
          }
          if(!isHave.value){
            console.log(isHave.value)
            form.value.outStoreId=null;
          }
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("获取货物信息失败！")
      }finally{
        loading.value = false
      }
    }else {
      queryStoreList()
    }

  }
  onMounted(()=>{
    queryAdminList()
    queryStoreList()
    queryStoreCommodityList()
  })
</script>

<style scoped>
    .form-container {
        display: flex;
        flex-direction: column;
        gap: 20px;
        width: 100%;
        position: relative;
    }

    .form-row {
        display: flex;
        gap: 20px;
        align-items: center;
        width: 100%;
    }

    .form-row > n-form-item {
        flex: 1;
    }

    .submit-row {
        justify-content: center;
        display: flex;
        width: 100%;
    }
</style>
